/*
 * @FilePath: /tads/server/app/business/service/bus.go
 * @Author: wnina0x0
 * @Date: 2025-04-15 15:00:43
 * @Description:
 *
 * 版权信息 : 2025 by wnina0x0, All Rights Reserved.
 */
package service

import (
	"fmt"
	"tads/server/app/business/models"
	"tads/server/app/business/service/dto"
	"tads/server/core/sdk/service"
)

type Bus struct {
	service.Service
}

func (b *Bus) GetBusList(r *[]models.BusType) error {
	var err error
	if err = b.Postgres.Where("is_deleted = ?", false).Find(r).Error; err != nil {
		b.Log.Errorf("总线获取错误：%s\n", err.Error())
		return err
	}
	return err
}

func (b *Bus) GetBus(d *dto.BusGetRequests) (*dto.BusGetResponse, error) {
	var err error
	var data []models.BusType
	count := 0
	res := dto.BusGetResponse{}
	if d.PageIndex <= 0 || d.PageSize <= 0 {
		d.PageIndex = 1
		d.PageSize = 10
	}

	limit := d.PageSize
	offset := (d.PageIndex - 1) * d.PageSize

	if err = b.Postgres.Offset(offset).Where(" bus_type_name ILIKE ? ", fmt.Sprintf("%%%s%%", d.BusTypeName)).Limit(limit).Find(&data).Error; err != nil {
		return res.NewPageResponse(count, d, data), err
	}
	count = len(data)
	if count == 0 {
		return res.NewPageResponse(count, d, data), nil
	}
	return res.NewPageResponse(count, d, data), nil
}

func (b *Bus) Inset(q *dto.BusInsetRequests) error {
	var err error
	var data models.BusType
	q.Generate(&data)
	if err = b.Postgres.Create(&data).Error; err != nil {
		return err
	}
	return nil

}

func (b *Bus) Update(q *dto.BusUpdateRequests) error {
	var err error
	var data models.BusType
	q.Generate(&data)
	if err = b.Postgres.Where(models.BusType{ID: q.ID}).Updates(&data).Error; err != nil {
		return err
	}
	return nil
}

func (b *Bus) Status(q *dto.BusStatusRequests) error {
	var err error
	var data models.BusType
	if err = b.Postgres.Model(&data).Where("id = ?", q.ID).Update("is_deleted", q.Status).Error; err != nil {
		return err
	}
	return nil
}
